﻿using H2O.Assistant.HostedServices;
using H2O.Assistant.Jobs;
using H2O.Assistant.QuartzExtensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NLog.Extensions.Logging;
using Quartz.Spi;
using System.IO;

namespace H2O.Assistant
{
    public class Host
    {
        public static IHostBuilder CreateDefaultBuilder(string[] args)
        {
            IHostBuilder hostBuilder = new HostBuilder()
                .ConfigureHostConfiguration(configHost =>
                {
                    configHost.SetBasePath(Directory.GetCurrentDirectory());
                    configHost.AddJsonFile("hostsettings.json", optional: true);
                    configHost.AddEnvironmentVariables(prefix: "NETCORE_");
                    configHost.AddCommandLine(args);
                })
                .ConfigureAppConfiguration((hostContext, configApp) =>
                {
                    configApp.AddJsonFile("appsettings.json", optional: true);
                    configApp.AddJsonFile(
                        $"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json",
                        optional: true);
                    configApp.AddEnvironmentVariables(prefix: "NETCORE_");
                    configApp.AddCommandLine(args);
                })
                .ConfigureServices((hostContext, services) =>
                {
                    if (hostContext.HostingEnvironment.IsDevelopment())
                    {
                        // Development service configuration
                    }
                    else
                    {
                        // Non-development service configuration
                    }
                    services.AddHostedService<LifetimeEventsHostedService>();
                    services.AddHostedService<TimedHostedService>();

                    // Quartz
                    services.AddSingleton<IJobFactory, CustomJobFactory>();
                    services.AddHostedService<QuartzHostedService>();
                    // Quartz Jobs
                    services.AddSingleton<HelloJob>();
                    services.AddSingleton<DingTalkJob>();
                    // 配置其他服务...
                })
                .ConfigureLogging((hostContext, loggingConfig) =>
                {
                    //loggingConfig.AddEventLog(); // *inux 下没有事件日志管理器, 看个鬼?
                    loggingConfig.AddNLog();
                })
                .UseConsoleLifetime();
            //XmlConfigurator.ConfigureAndWatch(
            //    repository: LogManager.GetRepository(repositoryAssembly: Assembly.GetEntryAssembly()),
            //    configFile: new FileInfo(fileName: "log4net.config"));
            return hostBuilder;
        }
    }
}
